#include "serversocket.h"
#include <errno.h>
#include <string.h>
ServerSocket::ServerSocket(unsigned int port){
	this->port = port;
	if( ( iSocketFD = socket(PF_INET, SOCK_STREAM, 0) ) <= 0 ){
		printf("initial error\n");
		exit(1);
	}
	SetSocketFD(iSocketFD);
}
ServerSocket::~ServerSocket(){}
int ServerSocket::Listen(int iBacklog){
	sockaddr_in addr;
	memset(&addr,0,sizeof(addr));
	addr.sin_family = PF_INET;
	addr.sin_port = htons(this->port);
	addr.sin_addr.s_addr = INADDR_ANY;
	//bind

	if( bind(this->iSocketFD, (sockaddr*)&addr, sizeof(sockaddr)) == -1){
		printf("%s",errno);
		printf("bind error\n");exit(1);
	}
	//listen
	if(listen(this->iSocketFD, iBacklog) == -1){
		printf("listen error\n");exit(1);
	}
	return 1;
}
Socket* ServerSocket::Accept(){
	sockaddr_in addr;
	socklen_t len_t = sizeof(addr);
	int fd = accept(iSocketFD, (sockaddr*)&addr, &len_t);
	printf("accept a new socket, fd is %d\n",fd);
	if(fd == -1){
		printf("%d %s\n",errno,strerror(errno));
		printf("accept error\n");
	}
	Socket* socket = new  Socket(fd);
	return socket;
}
int ServerSocket::IsServerSocket(){
	return 1;
}
